package cn.highedu.coolsharkhub.service.impl;

import cn.highedu.coolsharkhub.entity.Category;
import cn.highedu.coolsharkhub.entity.vo.CategoryManagementVO;
import cn.highedu.coolsharkhub.entity.vo.CategoryVO;
import cn.highedu.coolsharkhub.mapper.CategoryMapper;
import cn.highedu.coolsharkhub.service.CategoryService;
import cn.highedu.coolsharkhub.service.exception.BlankParameterException;
import cn.highedu.coolsharkhub.service.exception.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品类别业务层实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;
    @Override
    public List<CategoryVO> findHomepageCategories() {
        List<Category> categories = categoryMapper.selectAll();
        List<CategoryVO> categoryVOS = new ArrayList<>();
        for (Category category : categories) {
            if (category.getDisplay()) {
                categoryVOS.add(new CategoryVO(category.getId(), category.getName()));
            }
        }
        return categoryVOS;
    }

    /**
     * 查询后台管理页面商品类别
     * @return 后台中显示的商品类别
     */
    @Override
    public List<CategoryManagementVO> findManagementCategories() {
        return categoryMapper.selectAll()
                .stream().map(category -> {
                    // 把商品类别对象转换为后台商品管理对象
                    CategoryManagementVO categoryManagementVO = new CategoryManagementVO();
                    categoryManagementVO.setId(category.getId());
                    categoryManagementVO.setName(category.getName());
                    categoryManagementVO.setDisplay(category.getDisplay());
                    return categoryManagementVO;
                }).collect(Collectors.toList());
    }

    /**
     * 根据商品类别id删除商品类别
     * @param id 商品类别id 不能为null 必须为已存在的商品类别
     */
    @Override
    public void deleteById(Integer id) {
        if (id == null || id < 1) {
            throw new BlankParameterException("删除商品类别失败, 商品类别id不合法");
        }
        // 调用持久层删除方法
        int rows = categoryMapper.deleteById(id);
        if (rows < 1) {
            throw new EntityNotFoundException("删除商品类别失败, 类别不存在");
        }
    }
}
